package com.sup.purchase.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sup.purchase.mapper.PurchaseTableMapper;
import com.sup.goods.mapper.GoodsTableMapper;
import com.sup.purchase.domain.PurchaseTable;
import com.sup.purchase.service.IPurchaseTableService;
import com.sup.goods.domain.GoodsTable;

@Service
public class PurchaseTableServiceImpl implements IPurchaseTableService
{
    @Autowired
    private PurchaseTableMapper purchaseTableMapper;

    @Autowired
    private GoodsTableMapper goodsTableMapper;

    @Override
    public PurchaseTable selectPurchaseTableById(Long id)
    {
        return purchaseTableMapper.selectPurchaseTableById(id);
    }

    @Override
    public List<PurchaseTable> selectPurchaseTableList(PurchaseTable purchaseTable)
    {
        return purchaseTableMapper.selectPurchaseTableList(purchaseTable);
    }

    @Override
    @Transactional
    public int insertPurchaseTable(PurchaseTable purchaseTable)
    {
        // 1. 插入进货记录
        int rows = purchaseTableMapper.insertPurchaseTable(purchaseTable);

        // 2. 更新商品库存
        updateGoodsStock(purchaseTable.getPurProductId(), purchaseTable.getPurQuantity());

        return rows;
    }

    @Override
    @Transactional
    public int updatePurchaseTable(PurchaseTable purchaseTable)
    {
        // 获取原始进货记录
        PurchaseTable originalPurchase = purchaseTableMapper.selectPurchaseTableById(purchaseTable.getId());

        // 1. 更新进货记录
        int rows = purchaseTableMapper.updatePurchaseTable(purchaseTable);

        // 2. 计算数量差异并更新库存
        if(originalPurchase != null && !originalPurchase.getPurQuantity().equals(purchaseTable.getPurQuantity())) {
            int quantityDiff = purchaseTable.getPurQuantity() - originalPurchase.getPurQuantity();
            updateGoodsStock(purchaseTable.getPurProductId(), quantityDiff);
        }

        return rows;
    }

    @Override
    @Transactional
    public int deletePurchaseTableByIds(Long[] ids)
    {
        for(Long id : ids) {
            PurchaseTable purchase = purchaseTableMapper.selectPurchaseTableById(id);
            if(purchase != null) {
                // 减少商品库存（数量取负值）
                updateGoodsStock(purchase.getPurProductId(), -purchase.getPurQuantity());
            }
        }
        return purchaseTableMapper.deletePurchaseTableByIds(ids);
    }

    @Override
    @Transactional
    public int deletePurchaseTableById(Long id)
    {
        PurchaseTable purchase = purchaseTableMapper.selectPurchaseTableById(id);
        if(purchase != null) {
            // 减少商品库存（数量取负值）
            updateGoodsStock(purchase.getPurProductId(), -purchase.getPurQuantity());
        }
        return purchaseTableMapper.deletePurchaseTableById(id);
    }

    /**
     * 更新商品库存的私有方法
     */
    private void updateGoodsStock(Long goodsId, Integer quantity) {
        if(goodsId == null || quantity == null) return;

        GoodsTable goods = goodsTableMapper.selectGoodsTableById(goodsId);
        if(goods != null) {
            // 计算新库存
            long newStock = goods.getGoodsQuantity() + quantity;
            if(newStock < 0) {
                throw new RuntimeException("商品库存不能为负数");
            }
            goods.setGoodsQuantity(newStock);
            int updated = goodsTableMapper.updateGoodsTable(goods);
            if(updated == 0) {
                throw new RuntimeException("更新商品库存失败，可能已被其他操作修改");
            }
        } else {
            throw new RuntimeException("商品不存在，ID: " + goodsId);
        }
    }
}